package com.geiliwang.web.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.geiliwang.web.entity.Platform;
import com.geiliwang.web.entity.PlatformGroupVO;
import com.geiliwang.web.entity.Platformgroup;
import com.geiliwang.web.mapper.PlatformgroupMapper;
import com.geiliwang.web.service.PlatformService;
import com.geiliwang.web.service.PlatformgroupService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 邓
 * @since 2018-05-06
 */
@Service
public class PlatformgroupServiceImpl extends ServiceImpl<PlatformgroupMapper, Platformgroup> implements PlatformgroupService {

    @Autowired
    private PlatformgroupMapper platformgroupMapper;
    @Autowired
    private PlatformService platformService;

    @Override
    public List<Platformgroup> findAll() {
        EntityWrapper<Platformgroup> ew = new EntityWrapper<>();
        ew.where("delFlag='0'").orderBy("groupOrder",false);
        return platformgroupMapper.selectList(ew);
    }

    @Override
    public List<PlatformGroupVO> findAllGroup() {
        List<Platformgroup> platformgroupList = findAll();
        if(!CollectionUtils.isEmpty(platformgroupList)) {
            List<PlatformGroupVO> platformGroupVOList = platformgroupList.stream().map(group -> {
                PlatformGroupVO groupVO = new PlatformGroupVO();
                BeanUtils.copyProperties(group, groupVO);
                if (StringUtils.isNoneBlank(group.getPlatformIds())) {
                    //查询平台
                    EntityWrapper<Platform> ew = new EntityWrapper<>();
                    ew.where("delFlag='0'").in("id", Arrays.asList(group.getPlatformIds().split(",")));
                    List<Platform> platformList = platformService.selectList(ew);
                    Map<Long,Platform> platformMap = platformList.stream().collect(Collectors.toMap(Platform::getId, platform->platform));
                    platformList = Arrays.asList(group.getPlatformIds().split(",")).stream().map(str->{
                        Long strId = Long.parseLong(str);
                        return platformMap.get(strId);
                    }).collect(Collectors.toList());
                    groupVO.setPlatformList(platformList);
                }
                return groupVO;
            }).collect(Collectors.toList());
            return platformGroupVOList;
        }
        return Collections.emptyList();
    }
}
